/*
 * @Author: WangLi
 * @Date: 2024-03-10 09:13:33
 * @LastEditors: WangLi
 * @LastEditTime: 2024-05-10 19:20:19
 */
import WPage from "../../common/WPage";
import { guid } from "../../utils/util";
import { getUuid, writeBLECharacteristicValue } from "../../utils/common";
import { getDevice, setDevice, removeLastConnectedDevice } from "../../utils/storage";

const app = getApp();
WPage({
  data: {
    title: "功能列表",
    list: [],
  },
  onLoad(options) {
    this.init();
  },
  onShow() {
    this.init();
  },
  init() {
    this.getListData();
  },
  getListData() {
    const listData = [
      { id: guid(), name: "分享钥匙", code: "shareKeys", icon: "shareKeys" },
      {
        id: guid(),
        name: "操作日志",
        code: "operationLog",
        icon: "operationLog",
      },
      { id: guid(), name: "手动模式", code: "manualMode", icon: "manualMode" },
      { id: guid(), name: "接近开锁", code: "nearUnlock", icon: "nearUnlock" },
      {
        id: guid(),
        name: "固件升级",
        code: "firmwareUpgrade",
        icon: "firmwareUpgrade",
      },
      { id: guid(), name: "设备信息", code: "deviceInfo", icon: "deviceInfo" },
      { id: guid(), name: "删除钥匙", code: "deleteKeys", icon: "delete" },
    ];
    this.setData({ list: listData });
  },
  handleDeleteKeys() {
    const _this = this;
    const serviceId = getUuid("5506");
    writeBLECharacteristicValue(serviceId, getUuid("0062"), "", "", (res) => {
      console.log(res.code, app.globalData.deviceId, getDevice());
      if (res.code === 200) {
        const deviceList = getDevice();
        const currentDeviceList = deviceList.filter((item) => item.deviceId !== app.globalData.deviceId);
        setDevice(currentDeviceList);
        removeLastConnectedDevice();
        wx.showModal({
          title: "提示",
          content: "删除成功",
          showCancel: false,
          confirmText: "好",
          success() {
            _this.closeBLEConnection();
            wx.redirectTo({ url: "/pages/home/index" });
          },
        });
      } else {
        wx.showToast({
          title: "删除失败",
          icon: "error",
        });
      }
    });
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: app.globalData.deviceId,
      success() {
        console.log("closeBLEConnection success");
      },
      fail(error) {
        console.log("closeBLEConnection fail", error);
      },
    });
    app.globalData.deviceId = "";
  },
  onMenuClick(e) {
    const code = e.currentTarget.dataset.code;
    if (code === "deleteKeys") {
      wx.showModal({
        title: "提示",
        content: "确定要删除选中的钥匙？",
        success: (res) => {
          if (res.confirm) {
            this.handleDeleteKeys();
          }
        },
      });
    } else {
      wx.navigateTo({
        url: `/pages/${code}/index`,
        fail: () => {
          wx.showToast({
            title: "页面开发中...",
            icon: "error",
          });
        },
      });
    }
  },
});
